package com.aphrodite.io;

import java.io.IOException;
import java.io.InputStream;

public class IOUtil {
	private IOUtil() {}

	/**
	 * Reads the contents of a Input stream into a string with default buffer
	 * length
	 * 
	 * @param stream
	 * @param encoding
	 * @return
	 * @throws IOException
	 */
	public static String getString(InputStream stream, String encoding) throws IOException {
		return getString(stream, encoding, 1024);
	}

	/**
	 * Reads the contents of a Input stream into a string with specified buffer
	 * length
	 * 
	 * @param stream
	 * @param encoding
	 * @param bufferLength
	 * @return
	 * @throws IOException
	 */
	public static String getString(InputStream stream, String encoding, int bufferLength) throws IOException {
		byte[] buffer = new byte[bufferLength];
		int read;

		StringBuffer result = new StringBuffer();

		while ((read = stream.read(buffer, 0, bufferLength)) != -1) {
			if (encoding != null) {
				result.append(new String(buffer, 0, read, encoding));
			} else {
				result.append(new String(buffer, 0, read));
			}
		}

		return result.toString();
	}
}
